<!--
 * @docName: authorizaBusinessAccount授权企业公户
 * @Author: mwl
 * @Date: 16:03
 * @LastEditors: mwl
 * @LastEditTime: 16:03
-->
<template>
  <div class="content">
    <a-form-model ref="form" :model="form" :rules="rules" class="password-retrieval-form">
      <div class="input-info">
        <!--            <h2 class="title"></h2>-->
        <h2 class="title title1">提交验证</h2>
        <a-form-model-item label="开户行" prop="bankName" :label-col="labelCol" :wrapper-col="wrapperCol">
<!--          <a-input v-model="form.bankName" has-feedback placeholder="请填写开户行" type="text" />-->
          <a-select placeholder="请输入开户行"
                    show-search
                    v-model="form.bankName"
                    :default-active-first-option="false"
                    :show-arrow="false"
                    :filter-option="false"
                    :not-found-content="null"
                    @search="bankInfoListSearch"
                    @change="bankInfoListChange">
            <a-select-option v-for="item in bankInfoList" :key="item.bankName">
              {{ item.bankName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="开户支行" prop="subBankName" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-input v-model="form.subBankName" has-feedback placeholder="请填写开户支行" type="text" />
        </a-form-model-item>
        <a-form-model-item label="账户名称" prop="userName" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-input disabled v-model="form.userName"  placeholder="请填写账号名称" type="text" />
          <span style="line-height: 26px;display: block;margin-bottom: 10px; color: #d86767">仅支持当前企业公户充值</span>
        </a-form-model-item>
        <a-form-model-item prop="cityName" :label-col="labelCol" :wrapper-col="wrapperCol">
          <span slot="label"><i style="color: #f5222d;margin-right: 4px;">*</i>所在地</span>
          <div class="fixed-box">
            <a-select placeholder="请选择" v-model="province" style="width: 200px" @change="handleProvinceChange">
              <a-select-option v-for="province in provinceData" :key="province">
                {{ province }}
              </a-select-option>
            </a-select>
            -
            <a-select placeholder="请选择" v-model="secondCity" @select="cityCodeObtain" style="width: 200px">
              <a-select-option v-for="city in cityData" :key="city.id">
                {{ city.cityName }}
              </a-select-option>
            </a-select>
          </div>
        </a-form-model-item>
        <a-form-model-item label="银行账户" prop="bankAccountNo" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-input v-model="form.bankAccountNo" placeholder="请填写银行账户" type="text" />
        </a-form-model-item>
        <template>
          <a-form-model-item label="验证公户" :label-col="labelCol" :wrapper-col="wrapperCol">
            <span style="display: block;margin-bottom: 10px; color: #d86767">点击开始验证，您的账户将收到一笔打款（每天最多五次），请在输入框中输入收到的金额，验证是否正确</span>
            <a-button type="primary" :disabled="disabledButton" @click="verificationEventFun(masterType)">开始验证</a-button>
            <a-button type='link' v-if='form.verifyStatus == 0 && disabledButton' @click='modifyFun()'>修改</a-button>
          </a-form-model-item>
        </template>
      </div>
    </a-form-model>
    <a-divider />
    <a-form-model ref="form1" :model="form1" :rules="rule" class="password-retrieval-form" v-if='infoShow'>
      <div class="input-info">
        <h2 class="title title2">确认打款金额</h2>
        <a-form-model-item label="银行账户" required :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-input v-model="form1.bankAccountNo" :disabled="disabled" placeholder="请填写银行账户" type="text" />
        </a-form-model-item>
        <a-form-model-item label="收款金额" prop="verifyAmount" :label-col="labelCol" :wrapper-col="wrapperCol">
          <div style="margin-bottom: 10px;">
            <a-input-number style="min-width:200px;" :min="0" :formatter="limitTwoDigits" :parser="limitTwoDigits" placeholder="请填写收款金额" v-model="form1.verifyAmount" /> 元
          </div>
          <a-button type="primary" :label-col="labelCol" :wrapper-col="wrapperCol" :disabled="!disabledButton" @click="verificationOfPaymentEventFun(masterType)" >验证公户</a-button>
        </a-form-model-item>
      </div>
    </a-form-model>
  </div>
</template>

<script>
import { getAreaCodelist, getAreaCodeListProvince,getBankInfoList} from '@api/bankAccount'
import { limitDigits,cloneObject,conversionBranch } from '@/utils/util'
import { getSaveEntAccount, getEntAccountVerifyt, getEqueryEntDetail, getBusinessAccountInfo ,getSaveChannelAccount,getChannelAccountVerify,getBusinessAccountUpdateAccount } from '@api/account'
import { mapGetters } from 'vuex'

export default {
  name: 'authorizaBusinessAccount',
  data(){
    return {
      masterType:null,//1渠道账户 2企业账户
      entId:'',
      infoShow:false,
      businessAccountId:null,
      infoDetails:{},
      accountInfoDeatil:{},
      labelCol: { span: 3 },
      wrapperCol: { span: 10 },
      form:{
        subBankName: '',
        bankName:'',
        accountType:1,
        userName:'',
        bankAccountNo: '',
        legalName:''
      },
      provinceData:[],
      cityData:[],
      bankInfoList:[],
      secondCity:'',
      province:'',
      accountShow:true,
      entSetStatus:null,
      rules: {
        bankName:[{ required: true, message: '请填写开户行', trigger: 'blur' }],
        subBankName: [{ required: true, message: '请填写开户支行', trigger: 'blur' }],
        cityName: [
          { required: false, message: '请选择所在地', trigger: 'change' },
          { validator: this.validateSelect }
        ],
        bankAccountNo: [
          { required: true, message: '请填写银行账户', trigger: 'blur' },
          { validator: this.validateBankCard }
        ],
      },
      form1: {
        bankAccountNo: ''
      },
      rule: {
        bankAccountNo: [
          { required: true, message: '请填写银行账户', trigger: 'blur' },
          { validator: this.validateBankCard }
        ],
        verifyAmount: [{ required: true, message: '请填写收款金额', trigger: 'blur' }],
      },
      disabledButton: false,
      disabled: true
    }
  },
  mounted() {
  },
  created() {
    if(this.$route.query.masterType){
      this.masterType = this.$route.query.masterType
      if(this.$route.query.masterType == 1){
        this.form.userName = this.nickname();
        this.accountShow = false
      }
    }
    if(this.$route.query.bizId && this.$route.query.bizId !=1){
      this.entId = this.$route.query.bizId;
      this.getEqueryEntDetailFun();
    }
    this.getBusinessAccountInfoFun();
    this.getAreaCodeListProvinceFun();
    // this.getBankInfoListFun();
  },
  methods: {
    ...mapGetters(["nickname", "avatar","userInfo"]),
    //修改事件
    modifyFun(){
      if(this.disabledButton){
        this.disabledButton = false;
      };
      this.infoShow = false;
    },
    //开始验证按钮事件
    verificationEventFun(masterType){
      //1渠道账户 2企业账户
      if(masterType == 1){
        //accountInfoDeatil存在调修改 否则为新增
        this.getSaveChannelAccountFun()
      }else if(masterType == 2){
        this.onStartVerification();
      }
    },
    //打款认证按钮事件
    verificationOfPaymentEventFun(masterType){
      //1渠道账户 2企业账户
      if(masterType == 1){
        this.getChannelAccountVerifyFun()
      }else if(masterType == 2){

        this.accountSubmit();
      }
    },
    onChangeAccountType(e) {
      if(e.target.value == 1){
        this.disabledButton=false
      }else{
        this.disabledButton=true
      }
    },
    //校验为银行账户
    validateBankCard(rule,value,callback){
      let reg = /^([0-9]{7,30})$/;
      if (!value || reg.test(value)){
        callback();
      }else{
        callback("您的银行卡号格式不正确!");
      }
    },
    //校验所在地
    validateSelect(rule,value,callback){
      if (this.province && this.secondCity){
        if (this.form.cityCode){
          callback();
        }else{
          callback("请重新选择所在地!");
        }
      }else{
        callback("所在地不能为空!");
      }
    },
    //c查询企业详情
    getEqueryEntDetailFun(){
      let params = {};
      params.entId = this.entId;
      getEqueryEntDetail(params).then(res => {
        if (res.success) {
          // // 赋值表格数据
          this.infoDetails = res.result;
          this.form.userName = res.result.entDetailBase.entName;
          this.form.legalName = res.result.entDetailBase.legalName;
          this.entSetStatus = res.result.setStatus;
          this.loading = false;
        }else{
          this.$message.warning(res.message)
        }
      })
    },
    //获取省份列表
    getAreaCodeListProvinceFun(){
      let that = this;
      let params = {};
      getAreaCodeListProvince(params).then(res => {
        if (res.success) {
          // // 赋值表格数据
          that.provinceData = res.result;
          this.loading = false;
        }else{
          this.$message.warning(res.message)
        }
      })
    },
    //银行列表查询
    getBankInfoListFun(value){
      let that = this;
      let params = {};
      params.name = value;
      getBankInfoList(params).then(res => {
        if (res.success) {
          // // 赋值表格数据
          that.bankInfoList = res.result;
          this.loading = false;
        }else{
          this.$message.warning(res.message)
        }
      })
    },
    //获取城市编号等信息
    getAreaCodelistFun(province){
      let that = this;
      let params = {};
      params.provinceName = province;
      getAreaCodelist(params).then(res => {
        if (res.success) {
          // 赋值表格数据
          that.cityData = res.result;
          that.secondCity = that.cityData[0].cityName;
          that.form.cityCode = that.cityData[0].cityCode;
          that.form.cityName = that.secondCity;
          this.loading = false;
        }else{
          this.$message.warning(res.message)
        }
      })
    },
    //点击城市事件
    handleProvinceChange(value) {
      this.form.provinceName = value;
      this.getAreaCodelistFun(value)
      // this.cities = cityData[value];
    },
    //开户行选择
    bankInfoListSearch(value){
      console.log(value,'Search')
      if(value && value !='银行' && value !='银' && value !='行'){
        this.getBankInfoListFun(value);
      }
      console.log(this.bankInfoList)
    },
    bankInfoListChange(value){
      this.form.bankName = value;
      console.log(value,'Change')
    },
    //城市选择事件
    cityCodeObtain(value,label){
      for(let item of this.cityData){
        if(item.id == value){
          this.form.cityCode = item.cityCode;
          this.form.cityName = item.cityName;
        }
      }

    },
    /**
     * 验证字段
     * @param arr
     * @param callback
     */
    validateFields(arr, callback){
      let promiseArray = []
      for(let item of arr){
        let p = new Promise((resolve, reject) => {
          this.$refs['form'].validateField(item, (err)=>{
            if(!err){
              resolve();
            }else{
              reject(err);
            }
          })
        });
        promiseArray.push(p)
      }
      Promise.all(promiseArray).then(()=>{
        callback()
      }).catch(err=>{
        callback(err)
      })
    },
    //渠道开始校验
    getSaveChannelAccountFun(){
      // this.validateFields(['bankName','subBankName','cityName'], (error) => {
      //   if (!error) {
      this.$refs.form.validate(valid => {
        if (valid) {
          //执行
          let that = this;
          let params = {};
          params = that.form;
          getSaveChannelAccount(params).then(res => {
            if (res.success) {
              this.businessAccountId = res.result;
              this.disabledButton = true;
              this.form1.bankAccountNo = this.form.bankAccountNo;
              this.form.accountType = Number(this.form.accountType);
              this.infoShow = true;
              // this.accountQuery();
            }else{
              this.form.accountType = Number(this.form.accountType)
              this.$message.warning(res.message)
            }
          })
        }
      })

    },
    //渠道提交公户信息
    getChannelAccountVerifyFun(){
      this.$refs.form1.validate(valid => {
        if (valid) {
          let that = this;
          let params = {};
          let regA = cloneObject(that.form1);
          params = regA;
          params.verifyAmount = conversionBranch(regA.verifyAmount)
          params.businessAccountId = this.businessAccountId;
          getChannelAccountVerify(params).then(res => {
            if (res.success) {
              res.result ? this.$message.success("公户验证成功") : this.$message.warning("公户验证失败");
              this.disabledButton = false;
            }else{
              this.$message.warning(res.message)
            }
          })
        }
      })
    },
    //企业或个人开始校验
    onStartVerification(){
      // this.validateFields(['bankName','subBankName','cityName'], (error) => {
      //   if (!error) {
      this.$refs.form.validate(valid => {
        if (valid) {
          //执行
          let that = this;
          let params = {};
          params = that.form;
          console.log()
          if(that.form.accountType == 1 ){
            params.userName = that.form.userName;
          }else if(that.form.accountType == 2){
            params.userName = that.form.legalName;
          }
          params.masterId = this.$route.query.bizId;
          getSaveEntAccount(params).then(res => {
            if (res.success) {
              this.businessAccountId = res.result;
              this.disabledButton = true;
              this.form1.bankAccountNo = this.form.bankAccountNo;
              this.form.accountType = Number(this.form.accountType);
              this.infoShow = true;
              // this.accountQuery();
            }else{
              this.form.accountType = Number(this.form.accountType)
              this.$message.warning(res.message)
            }
          })
        }
      })

    },
    //提现拉取账户信息
    getBusinessAccountInfoFun(){
      let params = {};
      //1渠道账户 2企业账户
      params.masterType = this.masterType;
      if(this.$route.query.bizId){
        params.masterId = this.$route.query.bizId;
      }
      getBusinessAccountInfo(params).then(res => {
        if (res.success) {
          this.accountInfoDeatil = res.result;
          let data = cloneObject(res.result);
          if(!data){this.form.accountType = 2; return;}
          if(data.accountType){
            this.form.accountType = data.accountType;
          }else{
            this.form.accountType = 1;
          }

          this.form.bankAccountNo = data.bankAccountNo;
          this.form1.bankAccountNo = data.bankAccountNo;
          this.form.bankName = data.bankName;
          this.form.subBankName = data.subBankName;
          this.province = data.provinceName;
          this.secondCity = data.cityName;
          this.form.provinceName = data.provinceName;
          this.form.cityName = data.cityName;
          this.form.cityCode = data.cityCode;
          this.form.verifyStatus = data.verifyStatus;   //是否验证成功  -1取消验证;0-等待认证; 1-是; 2-否;
          this.disabledButton = false;
          if(data.verifyStatus == 0){
            this.infoShow = true;
            this.disabledButton = true;
          }

          this.loading = false;
        }else{
          this.$message.warning(res.message)
        }
      })
    },
    //企业个人提交公户信息
    accountSubmit(){
      // this.validateFields(['verifyAmount'], (Error) => {
      //   if (!Error) {
      this.$refs.form1.validate(valid => {
        if (valid) {
          let that = this;
          let params = {};
          let regA = cloneObject(that.form1);
          params = regA;
          params.verifyAmount = conversionBranch(regA.verifyAmount)
          params.businessAccountId = this.businessAccountId;
          params.masterId = this.$route.query.bizId;
          getEntAccountVerifyt(params).then(res => {
            if (res.success) {
              res.result ? this.$message.success("公户验证成功") : this.$message.warning("公户验证失败");
              this.disabledButton = false;
            }else{
              this.$message.warning(res.message)
            }
          })
        }
      })
    },
    //限制两位小数
    limitTwoDigits(value) {
      return limitDigits(value)
    },
  }
}
</script>

<style scoped lang="less">
.content{
  padding: 20px;
  background: #fff;
  .title{
    //padding: 20px;
    box-sizing: border-box;
    height: 44px;
    line-height: 35px;
    font-size: 16px;
    font-weight: 600;
    text-align: center;
    color: @primary-color;
    margin-bottom: 20px;
  }
  .title1{
    width: 161px;
    margin-top: 20px;
    padding-left: 20px;
    background: url("../../../assets/account/one.png") no-repeat;
    background-size: 100% 100%;
  }
  .title2{
    width: 196px;
    background: url("../../../assets/account/two.png") no-repeat;
    background-size: 100% 100%;
    padding-left: 20px;
  }
  .fixed-box{
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

/deep/.ant-tabs{
  padding: 1rem 2rem;
  width: 100%;
  box-sizing: border-box;
  background: #FFFFFF;
}
.icon{
  position: absolute;
  top: 0;
  right: 10px;
  color: #52c41a;
  font-size: 16px;
}

</style>
